package com.xc.service.Impl;

import com.alibaba.fastjson.JSON;
import com.xc.dao.RoomTypeMapper;
import com.xc.pojo.RoomType;
import com.xc.service.RoomTypeService;
import com.xc.utils.JedisPoolUtils;
import com.xc.utils.RedisKey;
import com.xc.vo.RoomTypeVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
public class RoomTypeServiceImpl implements RoomTypeService {
    @Resource
    private RoomTypeMapper roomTypeMapper;
    /**
     * 查询房型列表
     * @param roomTypeVo
     * @return
     */
    public List<RoomType> queryRoomTypeList(RoomTypeVo roomTypeVo) {
        return roomTypeMapper.queryRoomTypeList(roomTypeVo);
    }
    /**
     * 添加房型
     * @param roomType
     * @return
     */
    public int addRoomType(RoomType roomType) {
        //清空缓存
        JedisPoolUtils.getJedis().del(RedisKey.ROOM_TYPE_LIST);
        //设置已预订数量
        roomType.setReservedNum(0);
        //设置可入住房间数量
        roomType.setAvilableNum(roomType.getRoomNum());
        //设置已入住房间数量
        roomType.setLivedNum(0);
        return roomTypeMapper.addRoomType(roomType);
    }
    /**
     * 修改房型
     * @param roomType
     * @return
     */
    public int updateRoomType(RoomType roomType) {
        //清空缓存
        JedisPoolUtils.getJedis().del(RedisKey.ROOM_TYPE_LIST);
        //修改可用房间数
        roomType.setAvilableNum(roomType.getRoomNum());
        return roomTypeMapper.updateRoomType(roomType);
    }
    /**
     * 根据房型ID查询该房型下的房间数量
     * @param roomTypeId
     * @return
     */
    public int queryRoomCountByRoomTypeId(Integer roomTypeId) {
        return roomTypeMapper.queryRoomCountByRoomTypeId(roomTypeId);
    }
    /**
     * 删除房型
     * @param id
     * @return
     */

    public int deleteRoomType(Integer id) {
        //清空缓存
        JedisPoolUtils.getJedis().del(RedisKey.ROOM_TYPE_LIST);
        return roomTypeMapper.deleteById(id);
    }

    /**
     * 查询房型列表
     * @return
     */
    public String queryRoomTypeListByRedis() {
        //获取jedis
        Jedis jedis = JedisPoolUtils.getJedis();
        //从缓存读取ROOM_TYPE_LIST
        String room_type_list = jedis.get(RedisKey.ROOM_TYPE_LIST);
        //判断缓存是否为空
        if (StringUtils.isEmpty(room_type_list)){
            //为空  从数据库读取数据
            List<RoomType> roomTypes = roomTypeMapper.queryRoomTypeList(null);
            //把数据转换成JSON并保存到缓存中
            room_type_list = jedis.set(RedisKey.ROOM_TYPE_LIST, JSON.toJSONString(roomTypes));
        }
        return room_type_list;
    }
}
